'''
Created on Oct 8, 2009

@author: aamn
'''
import tables

from beetlelines import hammerindices

import matplotlib.pyplot as plt
from matplotlib import rc

import numpy as np
from numpy import rec

from pickle import dump

outfile = "/Users/aamn/Documents/Eclipse/workspace/pybeetle/src/hammer.dat"

infile = "/Users/aamn/Documents/Eclipse/workspace/pybeetle/IDL/indices.h5"
indices = tables.openFile(infile)
typeindices = indices.root.typeindices.read()
indices.close()
n_indices, n_indextemps = typeindices.shape
lindx = [foo['dictindex'] for foo in hammerindices.values()]
lines = [hammerindices.keys()[lindx.index(foo)] for foo in range(n_indices)]

# 3900,3,67 array
# [elements,axis,type]
# axis = [wave, flux, map]; only element 0 of the 3rd axis has real value.
# it represents the mapping from the apparent type to the real template type.
# sort of does the same thing as the templatetomap below. For example,
# the indices for spectral types O0 to O5 are all from the O5 template,
# which is the first element of the typetemplate array [0]

infile = "/Users/aamn/Documents/Eclipse/workspace/pybeetle/IDL/templates.h5"
templates = tables.openFile(infile)
typetemplates = templates.root.templatearray.read()
templates.close()
n_pixels, n_saxis, n_types = typetemplates.shape

possibletypes = ['O0', 'O1', 'O2', 'O3', 'O4', 'O5', 'O6', 'O7', 'O8', 'O9',
								'B0', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9',
								'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9',
								'F0', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9',
								'G0', 'G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8', 'G9',
								'K0', 'K1', 'K2', 'K3', 'K4', 'K5', 'K7',
								'M0', 'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9',
								'L0', 'L1', 'L2', 'L3', 'L4', 'L5', 'L6', 'L7', 'L8', 'L9',
								'T0', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'T9']
templatetomap = [0, 0, 0, 0, 0, 0, 1, 1, 2, 3,
								4, 5, 5, 6, 6, 7, 8, 9, 10, 11,
								12, 13, 14, 15, 16, 17, 18, 19, 20, 20,
								21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
								31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
								41, 42, 43, 44, 45, 46, 47,
								48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
								58, 59, 60, 61, 62, 63, 64, 65, 66, 66,
								66, 66, 66, 66, 66, 66, 66, 66, 66, 66]
actual2actual = np.int8(typetemplates[0, 2, :])


x = range(0, n_indextemps)	# the indices stop at L8.
actualtypes = [possibletypes[foo] for foo in x]
actualtomap = [templatetomap[foo] for foo in x]
typetemplates[0, 2, :]
show = [10, 20, 30, 40, 50, 60, 70]

# dictionary mapping; all items "tagged" as dmap['A0']['indices']['Halpha']
# or dmap['A0']['spectrum']['wave'] (or flux or actual type)
dmap = {}
for k in x:
	storeindices = {}
	storespectra = {}
	for foo in lines:
		storeindices[foo] = typeindices[hammerindices[foo]['dictindex'], k]
	storespectra['actualtype'] = actualtypes[actual2actual[actualtomap[k]]]
	storespectra['waves'] = typetemplates[:, 0, actualtomap[k]]
	storespectra['flux'] = typetemplates[:, 1, actualtomap[k]]
	dmap[actualtypes[k]] = {'indices':storeindices,
												'spectrum':storespectra,
												'dictindex':k}

f = open(outfile, 'w')
dump(dmap, f)
f.close()
# recarray mapping->
#		imap is indices table:  imap['Halpha']
#		smap is spectral types: smap['A0']
imap = rec.fromarrays(typeindices, names = lines)
smap = rec.fromarrays(typeindices.T, names = actualtypes)

# plotting tests and matplotlib learning
pext = ['.eps', '.png', '.pdf', '.svg']
fext = '.png'
fdir = '/tmp/Plots/'

checks = [None]
checks = lines
checks = ['MgI5172']
sptall = ['B1', 'B2', 'A8', 'A9', 'K3', 'M0', 'M4']
#sptall = ['G2']

try:
	for check in checks:
		if check is not None:
			try:
				#y = typeindices[coveyindices[check]['dictindex'], :]
				y = imap[check]
				fig = plt.figure()
				ps1 = fig.add_subplot(111)
				ps1plot = ps1.plot(x, y, 'ro')
				xlim = ps1.set_xlim(x[0], x[-1])
				ylim = ps1.get_ylim()
				xticks = ps1.xaxis.set_ticks([x[foo] for foo in show])
				xticklabels = ps1.xaxis.set_ticklabels([actualtypes[foo] for foo in show])
				xlabel = ps1.set_xlabel('Spectral Type')
				ylabel = ps1.set_ylabel(hammerindices[check]['title'])
#
				for sptone in sptall:
					ff = 0.02
					xo = actualtypes.index(sptone)
					yo = dmap[sptone]['indices'][check]

					ps1hline = ps1.axhline(y = yo, color = 'b', alpha = 0.5, linestyle = '-',
															xmin = (1. * xo - xlim[0]) / (xlim[1] - xlim[0]) - ff,
															xmax = (1. * xo - xlim[0]) / (xlim[1] - xlim[0]) + ff,
															)
					ps1vline = ps1.axvline(x = xo, color = 'b', alpha = 0.5, linestyle = '-',
															ymin = (1. * yo - ylim[0]) / (ylim[1] - ylim[0]) - ff,
															ymax = (1. * yo - ylim[0]) / (ylim[1] - ylim[0]) + ff,
															)
					ps1anno1 = ps1.annotate(sptone + ', ' + str(yo)[0:4],
															xy = (xo, yo), xycoords = 'data',
															xytext = (30, 30), textcoords = 'offset points',
															arrowprops = dict(alpha = 0.5, color = 'g',
																							arrowstyle = "->",
#																							linestyle = '-',
																							connectionstyle = "arc3,rad=.3"
																							),
															fontsize = 9)
#
				plt.savefig(fdir + check + fext)
			except:
				if not hammerindices.has_key(check): print 'there is no  key ' + check
			else:
				print 'continuing. I used this backend: ' + plt.rcParams['backend'] + \
				' and this output: ' + fext
except:
	print 'sorry you could not make that plot.'
else:
	print 'all done making plots'





#


